//
//  InviteFriendViewController.m
//  Gruphoto
//
//  Created by Thao Nguyen Huy on 1/8/13.
//  Copyright (c) 2013 CNC Software. All rights reserved.
//

#import "InviteFriendViewController.h"
#import "InviteFriendCell.h"
#import <AddressBook/AddressBook.h>
#import "ABContactsHelper/ABContactsHelper.h"

@interface InviteFriendViewController ()

@end

@implementation InviteFriendViewController

@synthesize friendSearchBar, friendTableView;
@synthesize inviteTypeButtons, code, isPrivate;
@synthesize contactsHaveEmail, contactsHavePhone, contactsNeedDisplay;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        UIImageView *titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"title_gruphoto.png"]];
        self.navigationItem.titleView = titleImageView;
        [titleImageView release];
        
        UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelButton setBounds:CGRectMake(0, 0, 51, 30)];
        [cancelButton setBackgroundImage:[UIImage imageNamed:@"button_cancel.png"] forState:UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *cancelButtonItem = [[UIBarButtonItem alloc] initWithCustomView:cancelButton];
        self.navigationItem.leftBarButtonItem = cancelButtonItem;
        [cancelButtonItem release];
        
        UIButton *doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [doneButton setBounds:CGRectMake(0, 0, 51, 30)];
        [doneButton setBackgroundImage:[UIImage imageNamed:@"button_done.png"] forState:UIControlStateNormal];
        [doneButton addTarget:self action:@selector(doneButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *doneButtonItem = [[UIBarButtonItem alloc] initWithCustomView:doneButton];
        self.navigationItem.rightBarButtonItem = doneButtonItem;
        [doneButtonItem release];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"background_navigation_bar.png"]
                                                      forBarMetrics:UIBarMetricsDefault];
    }
    self.view.backgroundColor = [UIColor colorWithRed:226/255.0 green:231/255.0 blue:237/255.0 alpha:1.0];
    
    friendTableView.backgroundColor = [UIColor colorWithRed:226/255.0 green:231/255.0 blue:237/255.0 alpha:1.0];
    friendSearchBar.backgroundImage = [UIImage imageNamed:@"background_searchbar.png"];
    
    inviteType = InviteViaSMS;
    self.contactsHavePhone = [NSMutableArray array];
    self.contactsHaveEmail = [NSMutableArray array];
    
    NSArray *allContacts = [ABContactsHelper contacts];
    for(ABContact *contact in allContacts){
        if (contact.emailDictionaries.count > 0) {
            [contactsHaveEmail addObject:contact];
        }
        if (contact.phoneDictionaries.count > 0) {
            [contactsHavePhone addObject:contact];
        }
    }
    NSLog(@"emails: %@", contactsHaveEmail);
    NSLog(@"phone: %@", contactsHavePhone);
    [self resetSearch];
    [friendTableView reloadData];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.friendSearchBar = nil;
    self.friendTableView = nil;
    self.inviteTypeButtons = nil;
}

- (void)dealloc {
    self.inviteTypeButtons = nil;
    self.contactsHavePhone = nil;
    self.contactsHaveEmail = nil;
    self.contactsNeedDisplay = nil;
    self.code = nil;
    [friendSearchBar release];
    [friendTableView release];
    [inviteTypeButtons release];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Custom methods
- (void)resetSearch {
    NSMutableArray *contactCopy = nil;
    if (inviteType == InviteViaEmail) {
        contactCopy = [self.contactsHaveEmail mutableCopy];
    }
    else {
        contactCopy = [self.contactsHavePhone mutableCopy];
    }
	self.contactsNeedDisplay = contactCopy;
	[contactCopy release];
}

- (void)handleSearchForTerm:(NSString *)searchTerm {
	NSMutableArray *contactsToRemove = [[NSMutableArray alloc] init];
	[self resetSearch];
    for (ABContact *contact in contactsNeedDisplay) {
        NSString *name = @"";
        if (contact.firstname) {
            name = contact.firstname;
        }
        if (contact.lastname) {
            name = [NSString stringWithFormat:@"%@ %@", name, contact.lastname];
        }
        if ([name rangeOfString:searchTerm
                        options:NSCaseInsensitiveSearch].location == NSNotFound)
            [contactsToRemove addObject:contact];
    }
    [contactsNeedDisplay removeObjectsInArray:contactsToRemove];
	[contactsToRemove release];
	[friendTableView reloadData];
}

#pragma mark - Action methods
- (IBAction)cancelButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)doneButtonPressed:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)inviteTypeButtonPressed:(id)sender {
    inviteType = [sender tag];
    for (UIButton *button in inviteTypeButtons) {
        if (button.tag == inviteType) {
            button.enabled = NO;
        }
        else {
            button.enabled = YES;            
        }
    }
    friendSearchBar.text = @"";
    [friendSearchBar resignFirstResponder];
    [self resetSearch];
    [friendTableView reloadData];
}

- (IBAction)inviteFriendButtonPressed:(id)sender {
    NSInteger tag = [sender tag];
    if (inviteType == InviteViaSMS) {
        ABContact *contact = [contactsHavePhone objectAtIndex:tag];
        NSString *phone = @"";
        BOOL received = NO;
        NSArray *phoneArray = [contact phoneDictionaries];
        for (NSDictionary *dict in phoneArray){
            if ([[dict objectForKey:@"label"] isEqualToString:@"mobile"] || [[dict objectForKey:@"label"] isEqualToString:@"iPhone"]) {
                phone = [dict objectForKey:@"value"];
                received = YES;
                break;
            }
        }
        if (!received) {
            NSDictionary *dict = [phoneArray objectAtIndex:0];
            phone = [dict objectForKey:@"value"];
        }
        
        if ([MFMessageComposeViewController canSendText]) {
            MFMessageComposeViewController *messageComposer = [[MFMessageComposeViewController alloc] init];
            NSString *body = @"Hey you! please join into my event on Gruphoto";
            if (isPrivate) {
                body = [NSString stringWithFormat:@"%@ with code %@", body, code];
            }
            [messageComposer setBody:body];
            messageComposer.recipients = [NSArray arrayWithObject:phone];
            messageComposer.messageComposeDelegate = self;
            [self presentModalViewController:messageComposer animated:YES];
            [messageComposer release];
        }
        else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning message"
                                                                message:@"SMS is not set on device"
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles: nil];
            [alertView show];
            [alertView release];
        }
    }
    else { // inviteType = InviteViaEmail
        ABContact *contact = [contactsHaveEmail objectAtIndex:tag];
        NSString *email = @"";
        NSArray *emailArray = [contact emailDictionaries];
        for (NSDictionary *dict in emailArray){
            email = [dict objectForKey:@"value"];
            break;
        }
        
        if ([MFMailComposeViewController canSendMail]) {
            MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
            mailComposer.mailComposeDelegate = self;
            [mailComposer setSubject:[NSString stringWithFormat:@"Invite from Gruphoto event"]];
            NSString *body = @"Hey you! please join into my event on Gruphoto";
            if (isPrivate) {
                body = [NSString stringWithFormat:@"%@ with code %@", body, code];
            }
            [mailComposer setMessageBody:body isHTML:NO];
            [mailComposer setToRecipients:[NSArray arrayWithObject:email]];
            [self presentModalViewController:mailComposer animated:YES];
            [mailComposer release];
        }
        else {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning message"
                                                                message:@"Email is not set on device"
                                                               delegate:self
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles: nil];
            [alertView show];
            [alertView release];
        }
    }
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
	NSString *searchTerm = [searchBar text];
	[self handleSearchForTerm:searchTerm];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchTerm {
	if ([searchTerm length] == 0) {
		[self resetSearch];
		[friendTableView reloadData];
		return;
	}
	[self handleSearchForTerm:searchTerm];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return contactsNeedDisplay.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *FriendCellId = @"InviteFriendCell";
    InviteFriendCell *cell = (InviteFriendCell *)[tableView dequeueReusableCellWithIdentifier:FriendCellId];
    if (cell == nil) {
        cell = [InviteFriendCell cellFromNib];
        [cell.inviteButton addTarget:self action:@selector(inviteFriendButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    }
    cell.inviteButton.tag = indexPath.row;
    ABContact *contact = [contactsNeedDisplay objectAtIndex:indexPath.row];
    NSString *name = @"";
    if (contact.firstname) {
        name = contact.firstname;
    }
    if (contact.lastname) {
        name = [NSString stringWithFormat:@"%@ %@", name, contact.lastname];
    }
    cell.nameLabel.text = name;
    
    if (inviteType == InviteViaSMS) {
        BOOL received = NO;
        NSArray *phoneArray = [contact phoneDictionaries];
        for (NSDictionary *dict in phoneArray){
            if ([[dict objectForKey:@"label"] isEqualToString:@"mobile"] || [[dict objectForKey:@"label"] isEqualToString:@"iPhone"]) {
                cell.emailOrPhoneLabel.text = [dict objectForKey:@"value"];
                received = YES;
                break;
            }
        }
        if (!received) {
            NSDictionary *dict = [phoneArray objectAtIndex:0];
            cell.emailOrPhoneLabel.text = [dict objectForKey:@"value"];
        }
    }
    else { // inviteType = InviteViaEmail
        NSArray *emailArray = [contact emailDictionaries];
        for (NSDictionary *dict in emailArray){
            cell.emailOrPhoneLabel.text = [dict objectForKey:@"value"];
            break;
        }
    }
    return cell;
}

#pragma mark - UITableViewDelegate
- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [friendSearchBar resignFirstResponder];
    return nil;
}

#pragma mark - MFMailComposeViewControllerDelegate & MFMessageComposeViewControllerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error {
    switch (result) {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail compose cancelled.");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail compose saved.");
            break;
        case MFMailComposeResultSent: {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Gruphoto message"
                                                                message:@"Invitation email was sent to your friend"
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
            break;
        }
        case MFMailComposeResultFailed: {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error message"
                                                                message:@"Failure to send email"
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
            break;
        }
        default:
            break;
    }
    [controller dismissModalViewControllerAnimated:YES];
}

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result {
    switch (result) {
        case MessageComposeResultCancelled:
            NSLog(@"Message compose cancelled.");
            break;
        case MessageComposeResultSent: {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Gruphoto message"
                                                                message:@"Invitation message was sent to your friend"
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
            break;
        }
        case MessageComposeResultFailed: {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error message"
                                                                message:@"Failure to send message"
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
            [alertView release];
            break;
        }
        default:
            break;
    }
    [controller dismissModalViewControllerAnimated:YES];
}

@end
